package com.sitech.portal.system.action;

import com.sitech.ibnms.core.BaseIbnmsAction;
import com.sitech.ibnms.core.IPage;
import com.sitech.ibnms.core.PageForm;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import com.sitech.portal.system.service.ISysLogInmsgService;
import com.sitech.util.UserSyncConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2015/6/10.
 */
public class UserSyncAction extends BaseIbnmsAction implements ServletRequestAware {

    private Logger logger = Logger.getLogger(UserSyncAction.class);

    private ISysLogInmsgService sysLogInmsgService;

    private Map<String, Object> param = new HashMap<String, Object>();

    private HttpServletRequest request;


    private Integer page;

    private Integer size;

    private String sort;

    public String getUserSyncList() {
        try {
            String keyName = "api-key";
            String key = request.getHeader(keyName);
            if (StringUtils.isEmpty(key)) {
                key = request.getParameter(keyName);
            }
            String ip = getIpAddr(request);
            logger.info("userSync interface  on request,request parameters:{page:" + page + ",size:" + size + "，sort:" +
                    sort + ",api-key:" + key + "};request ip:" + ip + ";requestTime:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .format(new Date()));
            if (StringUtils.isEmpty(key)) {
                return ERROR;
            }
            String ipList = UserSyncConfig.getKey(key);
            if (StringUtils.isEmpty(ipList) || ip == null) {
                return ERROR;
            }
            String[] ipArray = ipList.split(",");
            logger.info("Authorized ip list:" + StringUtils.join(ipArray, ","));
            boolean ifAuthorized = false;
            for (String s : ipArray) {
                if (ip.equals(s)) {
                    ifAuthorized = true;
                    break;
                }
            }
            logger.info("userSync interface Authorize ip:‘" + ip + "’ result:" + ifAuthorized);
            if (!ifAuthorized) {
                return ERROR;
            }
        } catch (Exception e) {
            logger.error("userSync interface Authorized  error", e);
            return ERROR;
        }
        Map<String, Collection<Map<String, Object>>> content = new HashMap<String, Collection<Map<String, Object>>>();

        Collection<TblSYS_LOGINMSG> rows = null;

        if (page == null || size == null) {
            rows = sysLogInmsgService.findUserAll();
        } else {
            PageForm pageForm = new PageForm(size, page, translateSort(sort), "asc");
            IPage pageData = sysLogInmsgService.selectUserByPage(pageForm);
            rows = pageData.getRows();
            Map<String, Object> pageObj = new HashMap<String, Object>();
            pageObj.put("size", size);
            pageObj.put("number", page);
            pageObj.put("totalElements", pageData.getRecords());
            pageObj.put("totalPages", pageData.getTotal());
            param.put("page", pageObj);
        }
        List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
        for (TblSYS_LOGINMSG row : rows) {
            Map<String, Object> user = new HashMap<String, Object>();
            user.put("userId", row.getLOGIN_ID());
            user.put("deptId", row.getDEPT_ID());
            user.put("name", row.getNAME());
            user.put("email", row.getEMAIL_ADDR());
            user.put("loginPhone", row.getLOGIN_PHONE());
            user.put("compId", row.getCOMP_ID());
            userList.add(user);
        }
        content.put("userList", userList);
        param.put("_embedded", content);
        return SUCCESS;
    }

    public Map<String, Object> getParam() {
        return param;
    }

    public void setSysLogInmsgService(ISysLogInmsgService sysLogInmsgService) {
        this.sysLogInmsgService = sysLogInmsgService;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public void setSize(Integer size) {
        this.size = size;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    private String translateSort(String sort) {
        if ("userId".equals(sort)) {
            return "LOGIN_ID";
        } else if ("name".equals(sort)) {
            return "NAME";
        } else if ("deptId".equals(sort)) {
            return "DEPT_ID";
        } else if ("compId".equals(sort)) {
            return "COMP_ID";
        } else if ("email".equals(sort)) {
            return "EMAIL";
        } else if ("loginPhone".equals(sort)) {
            return "LOGIN_PHONE";
        } else {
            return "";
        }
    }

    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest) {
        this.request = httpServletRequest;
    }

    private String getIpAddr(HttpServletRequest request) {
        return request.getRemoteAddr();
    }
}
